//
//  PPMemberListTableViewController.m
//  PetParadise
//
//  Created by 陈无忌 on 9/5/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPGroupMemberViewController.h"
#import "PPOtherUserCardViewController.h"
#import "PPUserCenterMainPageTableViewController.h"
#import "PPGroupInviteController.h"


#import "PPCustomBGTableView.h"
#import "PPMemberCollectionViewCell.h"
#import "PPGroupDetailTableViewCell.h"
#import "PPSystemConfiguraton.h"
#import "PPUserInfo.h"

typedef enum USER_PERMISSION
{
    OWNER = 0,
    MEMBER,
}USER_PERMISSION;

@interface PPGroupMemberViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate>

@property (nonatomic) int count;
@property (nonatomic, strong) PPSystemConfiguraton *config;
@property (weak, nonatomic) IBOutlet UICollectionView *memberCollectionView;
@property (weak, nonatomic) IBOutlet PPCustomBGTableView *groupInfoTableView;
@property (weak, nonatomic) IBOutlet UIButton *exitGroupButton;
@property (nonatomic) USER_PERMISSION type;

@end

@implementation PPGroupMemberViewController

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (void)fetchGroupInfo
{
    [[EaseMob sharedInstance].chatManager asyncFetchGroupInfo:self.groupConversation.targetId completion:^(EMGroup *group, EMError *error) {
        if (!error) {
            self.groupConversation.chatGroup.group = group;
            [self viewInit];
        }
        else{
            [PPHUD hudShowWithString:@"群组详情获取失败，请稍后再试" andView:self.view];
        }
    } onQueue:nil];
}

- (void)viewInit{
    [self.navigationItem setTitle:[NSString stringWithFormat:@"群聊信息(%@)",@(self.groupConversation.chatGroup.groupMember.count)]];
    NSString *usename = self.groupConversation.chatGroup.group.owners.firstObject;
    if (self.config.userInfo.id == [usename intValue]) {
        [self.exitGroupButton setTitle:@"解散该群" forState:UIControlStateNormal];
        self.type = OWNER;
    }else{
        [self.exitGroupButton setTitle:@"退出该群" forState:UIControlStateNormal];
        self.type = MEMBER;
    }
    
    [self.exitGroupButton addTarget:self action:@selector(exitButton) forControlEvents:UIControlEventTouchUpInside];
    [self.groupInfoTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self fetchGroupInfo];
    self.memberCollectionView.delegate = self;
    self.memberCollectionView.dataSource = self;
    self.groupInfoTableView.delegate = self;
    self.groupInfoTableView.dataSource = self;
    
    [self.memberCollectionView reloadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadView) name:@"memberChange" object:nil];
}

- (void)reloadView
{
    [self fetchGroupInfo];
    [self.memberCollectionView reloadData];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.groupInfoTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.groupInfoTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.groupInfoTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.groupInfoTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)exitButton{
    [[EaseMob sharedInstance].chatManager asyncLeaveGroup:self.groupConversation.targetId completion:^(EMGroup *group, EMGroupLeaveReason reason, EMError *error) {
        if (!error) {
            NSString *url;
            NSDictionary *params;
            if (self.type == MEMBER) {
                //用户自己退出
                url = [PPAPIList getAPIList].PPExitGroup;
                params = @{@"userId":@(self.config.userInfo.id),@"easeMobGroupId":self.groupConversation.targetId};
                
            }else{
                //群主解散
                url = [PPAPIList getAPIList].PPCloseGroup;
                params = @{@"userId":@(self.config.userInfo.id),@"easeMobGroupId":self.groupConversation.targetId};
            }
            [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber *processResult = responseObject[@"processResult"];
                if (processResult.boolValue) {
                    [PPHUD hudShowWithString:@"退出成功" andView:self.view];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"groupChange" object:nil];
                    int count = self.navigationController.viewControllers.count;
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:count - 3] animated:YES];
                }else{
                    [PPHUD hudShowWithString:@"退出失败" andView:self.view];

                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [PPHUD hudShowWithString:@"网络异常" andView:self.view];
            }];
        }else{
            [PPHUD hudShowWithString:@"退出失败" andView:self.view];
        }
    } onQueue:nil];
}

#pragma mark - Tabel view data source

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPGroupDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell"];
    
    if (indexPath.row == 0) {
        //群组名
        cell.titleLabel.text = @"群聊名称";
        cell.contentLabel.text = self.groupConversation.chatGroup.groupName;
    }else if (indexPath.row == 1) {
        //群组ID
        cell.titleLabel.text = @"群聊ID";
        cell.contentLabel.text = self.groupConversation.targetId;
    }else if (indexPath.row == 2){
        //群组人数
        cell.titleLabel.text = @"群聊人数";
        cell.contentLabel.text = [NSString stringWithFormat:@"%d/%d",self.groupConversation.chatGroup.groupMember.count,self.groupConversation.chatGroup.group.groupSetting.groupMaxUsersCount];
    }else{
        //设置背景
        cell.titleLabel.text = @"群聊背景";
        cell.contentLabel.text = @"";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - Collection view data source

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.type == OWNER) {
        return self.groupConversation.chatGroup.groupMember.count + 1;
    }else{
        return self.groupConversation.chatGroup.groupMember.count;
    }
    
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPMemberCollectionViewCell *cell = [self.memberCollectionView dequeueReusableCellWithReuseIdentifier:@"memberCell" forIndexPath:indexPath];
    
    if (indexPath.row == self.groupConversation.chatGroup.groupMember.count) {
        [cell.memberAvatar setImage:[UIImage imageNamed:@"addPetPhoto"]];
    }else{
        PPUserInfo *user = [self.groupConversation.chatGroup.groupMember objectAtIndex:indexPath.row];
        [cell.memberAvatar setImageWithURL:[PPImageUrl getImageUrl:user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.groupConversation.chatGroup.groupMember.count) {
        //invite
        PPGroupInviteController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPGroupInviteController"];
        targetVC.groupConversation = self.groupConversation;
        [self.navigationController pushViewController:targetVC animated:YES];
        
    }else{
        PPUserInfo *user = [self.groupConversation.chatGroup.groupMember objectAtIndex:indexPath.row];
        if (user.id == self.config.userInfo.id) {
            PPUserCenterMainPageTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPUserCenterMainPageTableViewController"];
            [self.navigationController pushViewController:targetVC animated:YES];
        }else{
            PPOtherUserCardViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCardViewController"];
            targetVC.user = user;
            [self.navigationController pushViewController:targetVC animated:YES];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
